package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;

import artid.com.arttogoa.R;

import artid.com.arttogoa.fragment.BindingIbeacon_Fragment;
import artid.com.arttogoa.parser.IbeaconActivityInfoParser;
import artid.com.arttogoa.parser.MyArtPush_IbactivityListBean;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：BindingIbeacon_Activity   
 * 类描述   ：Ibeacon绑定页面
 * 创建人   ：耿卫斌   
 * 创建时间：2016-11-8 下午1:43:07   
 *
 */
public class BindingIbeacon_Activity extends BaseActivity implements OnClickListener{
	private RadioGroup mRadioGroup;
	private RadioButton fixedFormatRB,customRB;
	private ViewPager mViewPager;
	private List<Fragment> fragementlist;
	private int whichActivity=0;//默认我的出售 （0：个人微站 1：自定义推广活动）
	private String action="新建";//默认动作为新建
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bindingibeacon);
		setContent(this, getIntent());
		setBack();
		mContext=this;
		initView();
	}

	private void initView(){
		initViewPage();
	}

	/**
	 * 初始化ViewPage
	 */
	private void initViewPage(){
		// 注册当前广播
		IntentFilter filter = new IntentFilter("com.BindingIbeacon_Activity.receiver");
		registerReceiver(broadcastReceiver, filter);
		whichActivity=getIntent().getIntExtra("bindingIbeacon_whichActivity", 0);
		MyArtPush_IbactivityListBean mMyArtPush_IbactivityListBean=(MyArtPush_IbactivityListBean) getIntent().getSerializableExtra("MyArtPush_IbactivityListBean");
		IbeaconActivityInfoParser mIbeaconActivityInfoParser=(IbeaconActivityInfoParser) getIntent().getSerializableExtra("IbeaconActivityInfoParser");
		action=getIntent().getStringExtra("action");
		mRadioGroup = (RadioGroup) findViewById(R.id.BindingIbeacon_RadioGroup);
		// 得到RadioGroup中的RadioButton按钮
		fixedFormatRB=(RadioButton) findViewById(R.id.BindingIbeacon_fixedFormatRB);
		fixedFormatRB.setOnClickListener(this);
		customRB=(RadioButton) findViewById(R.id.BindingIbeacon_customRB);
		customRB.setOnClickListener(this);
		mViewPager = (ViewPager) findViewById(R.id.BindingIbeacon_pager);
		fragementlist = new ArrayList<Fragment>();
		BindingIbeacon_Fragment fixedFormatFragment = new BindingIbeacon_Fragment(0,action,mMyArtPush_IbactivityListBean,mIbeaconActivityInfoParser);
		BindingIbeacon_Fragment customFragment = new BindingIbeacon_Fragment(1,action,mMyArtPush_IbactivityListBean,mIbeaconActivityInfoParser);
		if("编辑".equals(action)){
			whichActivity=getIntent().getIntExtra("type", 0);
			mRadioGroup.setVisibility(View.GONE);
			if(whichActivity==0){
				mTittle.setText("个人微站");
				fragementlist.add(fixedFormatFragment);
				fixedFormatRB.setChecked(true);
			}else if(whichActivity==1){
				mTittle.setText("自定义推广活动");
				fragementlist.add(customFragment);
				customRB.setChecked(true);
			}
		}else{
			mTittle.setText("绑定");
			fragementlist.add(fixedFormatFragment);
			fragementlist.add(customFragment);
		}
		mViewPager.setAdapter(new MyPageadapter(getSupportFragmentManager()));
		// 实现滑动 绑定监听（滑动页面并改变RadioButton的改变）
		mViewPager.setOnPageChangeListener(onPage);
		mViewPager.setCurrentItem(whichActivity);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.BindingIbeacon_fixedFormatRB:
			//个人微站
			mViewPager.setCurrentItem(0);
			break;
		case R.id.BindingIbeacon_customRB:
			//自定义推广活动
			mViewPager.setCurrentItem(1);
			break;
		default:
			break;
		}
	}

	// 实现滑动
	class MyPageadapter extends FragmentPagerAdapter {

		public MyPageadapter(FragmentManager fm) {
			super(fm);
			// TODO Auto-generated constructor stub
		}

		@Override
		public Fragment getItem(int arg0) {
			// TODO Auto-generated method stub
			return fragementlist.get(arg0);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return fragementlist.size();
		}
	}

	OnPageChangeListener onPage=new OnPageChangeListener(){

		// 滑动页面并改变RadioButton的改变
		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			if(position==0){
				fixedFormatRB.setChecked(true);
			}else if(position==1){
				customRB.setChecked(true);
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub

		}
	};

	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(
				mContext,
				Integer.parseInt(NetUtils.getDisplayMetrics(this).get(NetUtils.DM_WIDTH)),
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						switch (v.getId()) {
						case R.id.tv_phone:
							//检查权限
							if (ContextCompat.checkSelfPermission(BindingIbeacon_Activity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
								displayFrameworkBugMessageAndExit();
								return;
							}
							// 照相机
							CameraUtils.openCameraImage(BindingIbeacon_Activity.this);
							AlertUtils.dismiss();
							break;
						case R.id.tv_choice:
							// 从相册获取
							CameraUtils.openLocalImage(BindingIbeacon_Activity.this);
							AlertUtils.dismiss();
							break;
						default:
							break;
						}
					}
				});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri = CameraUtils.imageUriFromCamera;
			if (uri != null) {
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			} else {
				// 防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@SuppressWarnings("unused")
					@Override
					public void run() {
						if (uri != null) {
							Intent i = new Intent(mContext, Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			// 判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i = new Intent(mContext, Clip_Activity.class);
				i.putExtra("ImagePath",BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if (requestCode == 200) {
			if (data != null) {
				// 获取剪切后的图片路径
				String PhotoPath = data.getExtras().getString("PhotoPath");
				if (!StringUtils.isEmpty(PhotoPath)) {
					Log.d("log", PhotoPath);
					Intent intent0 = new Intent("com.BindingIbeacon_Fragment.receiver");  
					intent0.putExtra("Photo", true);
					intent0.putExtra("PhotoPath", PhotoPath);
					mContext.sendBroadcast(intent0);
				}
			}
		}
	}

	// 对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getBooleanExtra("Photo", false) == true) {
				//判断是否是由拍照或者获取本地图片
				showPopupWindow();
			}
		}
	};

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
